package com.netty.kkk.controller;

import com.alibaba.fastjson.JSONObject;
import com.netty.kkk.service.ChatService;
import com.netty.kkk.service.UserService;
import com.netty.kkk.vo.Message;
import com.netty.kkk.vo.MessageRecord;
import com.netty.kkk.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


@Component
@ServerEndpoint(value = "/groupChat/{groupId}/{userId}")
public class WebsocketGroupCrl {

    private static UserService userService;
    private static ChatService chatService;

    @Autowired
    public void setMyServiceImpl(UserService userService){
        WebsocketGroupCrl.userService = userService;
    }
    @Autowired
    public void setMyChatImpl(ChatService chatService){
        WebsocketGroupCrl.chatService = chatService;
    }

    public static int SendMsg_Type = 0;//发送消息 类型
    public static int OnLine_Type = 1;//上线 类型
    public static int Leaving_Type = 2;//离线 类型
    public static int DeleteChat_Type = 3;//删除频道
    public static int Quit_Type = 4;//退出频道
    public static int ChangeChatName_Type = 5;//改频道名


    public static ConcurrentHashMap<String, List<Session>> groupMemberMap = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, Map<String, UserInfo>> onLineUserMap = new ConcurrentHashMap<>();

    /**
     * 用户上线
     * @param session
     * @param groupId
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("groupId") String groupId, @PathParam("userId") String userId){
        List<Session> sessionList = groupMemberMap.computeIfAbsent(groupId, k -> new ArrayList<>());
        sessionList.add(session);
        UserInfo userInfo = userService.findUserByName(userId);
        Map<String, UserInfo> userInfoMap = onLineUserMap.computeIfAbsent(groupId, k -> new HashMap<>());
        userInfoMap.put(userId, userInfo);
        sendMsg(groupId, userId, "上线了", OnLine_Type);
    }

    /**
     * 群发消息
     * @param groupId
     * @param userId
     * @param message
     */
    @OnMessage
    public void onMessage(@PathParam("groupId") String groupId, @PathParam("userId") String userId, String message){
        System.out.println(groupId+"---"+userId+"----发送----"+message);
        recordMsg(groupId, userId, message);
        sendMsg(groupId, userId, message, SendMsg_Type);
    }

    /**
     * 用户离线
     * @param session
     * @param groupId
     * @param userId
     */
    @OnClose
    public void onClose(Session session, @PathParam("groupId") String groupId, @PathParam("userId") String userId){
        groupMemberMap.get(groupId).remove(session);
        if(onLineUserMap.get(groupId).containsKey(userId)){
            System.out.println("groupId:"+groupId+"---userId:"+userId+"---离开了");
            sendMsg(groupId, userId, "离开了", Leaving_Type);
        }
    }

    /**
     * 发送消息
     * @param groupId 群聊id
     * @param userId  用户id
     * @param msg     消息内容
     * @param messageType   消息类型
     */
    public void sendMsg(String groupId, String userId, String msg, int messageType){
        Message message = new Message();
        message.setMsg(msg);
        message.setTime(new Date());
        message.setUserInfo(onLineUserMap.get(groupId).get(userId));
        message.setMessageType(messageType);
        if (messageType == Leaving_Type || messageType == Quit_Type){
            onLineUserMap.get(groupId).remove(userId);
        }
        if (messageType == OnLine_Type || messageType == Leaving_Type || messageType == Quit_Type){
            List<UserInfo> onlineUser = new ArrayList<UserInfo>(onLineUserMap.get(groupId).values());
            List<String> onlineNickName = new ArrayList<>();
            for (UserInfo userInfo : onlineUser){
                onlineNickName.add(userInfo.getNickName());
            }
            message.setOnlineMember(onlineNickName);
        }
        //遍历群发消息
        try{
            for (Session session : groupMemberMap.get(groupId)){
                String text = JSONObject.toJSONString(message);
                session.getBasicRemote().sendText(text);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private void recordMsg(String groupId, String userId, String message){
        MessageRecord messageRecord = new MessageRecord();
        UserInfo userInfo = userService.findUserByName(userId);
        messageRecord.setChatId(groupId);
        messageRecord.setUserNickNameFrom(userInfo.getNickName());
        messageRecord.setHeadUrl(userInfo.getAvatarUrl());
        messageRecord.setFirstLetter(userInfo.getFirstLetter());
        messageRecord.setTime(new Date());
        messageRecord.setMessage(message);
        messageRecord.setUserNameFrom(userInfo.getUserName());

        chatService.recordMsg(messageRecord);
    }

}
